# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""The logging objcet for DataZoomer"""


from time import strftime, localtime, asctime
import os

class EventLog:
    tablename = 'dz_log'

    def __init__(self,zoomer):
        self.zoomer = zoomer
        self.db = zoomer.db

    def exec_SQL(self,cmd):
        return self.db(cmd)

    def log(self,status,comment):
        zoomer = self.zoomer

        if os.environ.has_key('REMOTE_USER'):
            user = os.environ['REMOTE_USER']
        elif zoomer.loginid:
            user = self.zoomer.loginid
        else:
            user = ''

        if os.environ.has_key('REMOTE_ADDR'):
            addr = os.environ['REMOTE_ADDR']
        else:
            addr = 'n/a'

        if os.environ.has_key('REMOTE_HOST'):
            host = os.environ['REMOTE_HOST']
        else:
            host = 'unknown'

        if zoomer.app:
            try:
                appname = zoomer.app.name
            except:
                appname = '!'
        else:
            appname = 'unknown'

        jobid = ''
        if zoomer.jobticket and zoomer.jobticket.getid(): jobid = '%10.10d' % zoomer.jobticket.getid()

        cmd = "INSERT INTO %s" % self.tablename
        cmd = cmd + " VALUES (0,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        args = (
            appname,
            ('%s.%s' % (zoomer.webvars.con,zoomer.webvars.action))[:50],
            jobid,
            status,
            user,
            addr,
            host,
            strftime('%Y-%m-%d',localtime()),
            asctime()[11:19],
            comment)

        zoomer.db.execute(cmd,args)

    def dump(self):
        cmd = "SELECT * FROM %s order by entryid desc" % (self.tablename)
        curs = self.exec_SQL(cmd)
        import base64
        count = 0
        for rec in curs:
            print rec
            count += 1
            if count > 20:
                break


if __name__ == '__main__':
    class App:
          pass
    import unittest
    class LogTest(unittest.TestCase):
        def test(self):
          from datetime import date
          from zoom import zoomer
          zoomer.db('delete from dz_log where user="datazoomerTesting"')
          zoomer.db('delete from dz_log where user="remote user"')
          zoomer.loginid = 'datazoomerTesting'
          zoomer.app = App()
          zoomer.app.name = 'Test App'
          log = EventLog(zoomer)
          log.app    = 'test'
          log.pageid = 'page1'
          log.log('I','This is a test')
          self.assertEqual(len(zoomer.db('select * from dz_log where user="datazoomerTesting"').__dict__['data']),1)
          rec = zoomer.db('select * from dz_log where user="datazoomerTesting"')[0]
          self.assertEqual(rec.PRODUCT,'Test App')
          self.assertEqual(rec.STATUS,'I')
          self.assertEqual(rec.USER,'datazoomerTesting')
          self.assertEqual(rec.COMMENT,'This is a test')
          zoomer.db('delete from dz_log where user="datazoomerTesting"')
          os.environ['REMOTE_ADDR'] = 'remote address'
          os.environ['REMOTE_USER'] = 'remote user'
          os.environ['REMOTE_HOST'] = 'remote host'
          zoomer.webvars.view = 'page'
          zoomer.webvars.action = 'one'
          log.log('P','This is second test')
          self.assertEqual(len(zoomer.db('select * from dz_log where user="remote user"').__dict__['data']),1)
          rec = zoomer.db('select * from dz_log where user="remote user"')[0]
          self.assertEqual(rec.REMOTEADDR,'remote address')
          self.assertEqual(rec.USER,'remote user')
          self.assertEqual(rec.MACHINE,'remote host')
          self.assertEqual(rec.PRODUCT,'Test App')
          self.assertEqual(rec.STATUS,'P')
          self.assertEqual(rec.COMMENT,'This is second test')
          self.assertEqual(rec.PAGEID,'page.one')
          self.assertEqual(rec.DATE,date.today())
    unittest.main()
